package com.dongdongshop.service.imp;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbGoodsVo;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@org.springframework.stereotype.Service
public class FreemarkerServiceImpl implements FreemarkerService {
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${freemarker.outDir}")
    private String outDir;
    @Reference
    private GoodsService goodsService;
    @Reference
    private GoodsDescService goodsDescService;
    @Reference
    private GoodsItemService goodsItemService;


    @Override
    public void createPage(Long[] ids) {
        //获取模板
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter fileWriter = null;
        try {
            Template template = configuration.getTemplate("item.ftl");
            for (int i = 0; i < ids.length; i++) {
                TbGoods tbGoods = goodsService.getById(ids[i]);
                TbGoodsDesc tbGoodsDesc = goodsDescService.getById(ids[i]);
                List<TbItem>  list = goodsItemService.selectByGoodsId(ids[i]);
                TbGoodsVo tbGoodsVo = goodsService.getItemName(ids[i]);
                for (TbItem t : list) {

                }
                //创建数据模型
                Map<String,Object> map = new HashMap<>();
                map.put("goods",tbGoods);
                map.put("goodsDesc",tbGoodsDesc);
                map.put("itemlist",list);
                map.put("vo",tbGoodsVo);
                //创建输出对象
                fileWriter = new FileWriter(outDir+ids[i]+".html");
                //输出页面
                template.process(map,fileWriter);
                System.out.println(111111);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileWriter!=null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
